import { createRouter, createWebHistory } from 'vue-router'
// @ts-ignore
import HomeMain from '../views/home/HomeMain.vue'
// @ts-ignore
import Home from '../views/home/Home.vue'
// @ts-ignore
import ShoppingCart from '../views/ShoppingCartView.vue'
import Collection from "@/views/CollectionView.vue";
import Order from "@/views/OrderView.vue";
import Login from "@/views/Login.vue";
import Member from "@/views/Member.vue";
import UserInfo from "@/views/UserInfoView.vue";
import Message from '@/views/Message.vue';
import { useUserStore } from "@/stores/user";
import StoreView from "@/views/StoreView.vue";
import Pay from '@/components/pay.vue' // 引入用户状态管理
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: { title: '登录页面' } // 添加页面标题
    },
    {
      path: '/message',
      name: 'message',
      component: Message,
      meta: { title: '消息页面' } // 添加页面标题
    },
    {
      path: '/',
      name: 'home',
      component: Home,
      redirect: '/homeMain',
      meta: { title: '首页' }, // 添加页面标题
      children: [
        {
          path: 'homeMain',
          name: 'homeMain',
          component: HomeMain,
          meta: { title: '首页' } // 添加页面标题
        },
        {
          path: 'collection',
          name: 'collection',
          component: Collection,
          meta: { requiresAuth: true, title: '我的收藏' } // 添加页面标题
        },
        {
          path: 'member',
          name: 'member',
          component: Member,
          meta: { requiresAuth: true, title: '会员中心' } // 添加页面标题
        },
        {
          path: 'order',
          name: 'order',
          component: Order,
          meta: { requiresAuth: true, title: '我的订单' } // 添加页面标题
        },
        {
          path: 'shoppingCart',
          name: 'shoppingCart',
          component: ShoppingCart,
          meta: { requiresAuth: true, title: '购物车' } // 添加页面标题
        },
        {
          path: 'userInfo',
          name: 'userInfo',
          component: UserInfo,
          meta: { requiresAuth: true, title: '用户信息' } // 添加页面标题
        }
      ]
    },
    {
      path: '/store/:brandId',
      name: 'StoreView',
      component: StoreView,
      meta: { title: '店铺详情' } // 添加页面标题
    },
    {
      path: '/alipay/pay/:traceNo',
      name: 'AlipayPay',
      component: Pay,
      meta: { title: '支付页面' } // 添加页面标题
    }
  ]
})

// 添加全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore(); // 获取用户状态
  const requiresAuth = to.meta.requiresAuth; // 检查目标路由是否需要登录
  if (to.meta.title) {
    document.title = to.meta.title as string;
  }
  if (requiresAuth && !userStore.token) {
    // 如果需要登录且用户未登录，重定向到登录页面
    next({ name: "login" });
  } else {
    // 否则允许访问
    next();
  }
});
export default router
